﻿

var queryDoctorListUrl = ArrangeUrl + "/Doctor/getDoctorList";
var newDisplayRuleUrl = ArrangeUrl + "/HsProgram/save";
var queryDisplayRuleInfoUrl = ArrangeUrl + "/HsProgram/getParamByProgramId";
var updateDisplayRuleInfoUrl = ArrangeUrl + "/HsProgram/updete";
var queryTemplateInfoUrl = ArrangeUrl + "/HsTemplate/getTemplateById";

var _disrule_id = "";

$(function () {

    //loadDept_t("select_dept");

    _disrule_id = GetQueryString("rule_id");
    var ruleName = unescape(getCookie("_RULENAME_" + _disrule_id));

    if (_disrule_id != "" && _disrule_id != null) {
        loadDisplayRuleInfo();
        $(".s_title").html("修改显示规则-" + ruleName);
    } else {
        queryDoctor();
    }

});



function loadDept_t(divId) {

    $.ajax({
        url: queryDeptListUrl,
        type: 'get',
        async: false,
        success: function (d) {
            if (JSON.parse(d).status == "0") {
                var menuListObj = new Object;
                var deptItems = JSON.parse(d).data;

                var opHtml = "<option value=''>全部</option>";
                for (var i = 0; i < deptItems.length; i++) {
                    var _deptId = deptItems[i].deptId;
                    var _deptName = deptItems[i].deptName;
                    var _parentId = deptItems[i].parentId;
                    var _deptLevel = deptItems[i].deptLevel;

                    if (_deptLevel == "1") {
                        opHtml += "<option style='color:#F16524' value='" + _deptId + "'>" + _deptName + "</option>";
                        var opstr = queryDeptNodes_t(deptItems, _deptId);
                        if (opstr != "") {
                            opHtml += opstr;
                        }
                    }
                }
                $("#" + divId).html(opHtml);
            }
        }
    });
}

//查询科室2-3级
function queryDeptNodes_t(jsonData, deptId) {

    var opHtml = "";

    for (var i = 0; i < jsonData.length; i++) {
        var _deptId = jsonData[i].deptId;
        var _deptName = jsonData[i].deptName;
        var _parentId = jsonData[i].parentId;
        var _deptLevel = jsonData[i].deptLevel;

        if (_parentId == deptId) {

            if (_deptLevel == "2") {
                opHtml += "<option style='color:#58DCAD' value='" + _deptId + "'>&nbsp;&nbsp;├ " + _deptName + "</option>";
            }
            else if (_deptLevel == "3") {
                opHtml += "<option  style='color:#4EA3F9' value='" + _deptId + "'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├ " + _deptName + "</option>";
            }
            var nodeHtml = queryDeptNodes(jsonData, _deptId);
            if (nodeHtml != "") {
                opHtml += nodeHtml;
            }
        }
    }
    return opHtml;
}


//打开模板选择窗口
function queryTemplate() {

    layer.open({
        type: 2,//加载外部页面类型
        closeBtn: 1,
        title: "选择模板",//不显示标题栏
        // shadeClose: true,//点其他地方自动关闭
        area: ['800px', '500px'],
        content: '../arrange/select_template.html',
    });
}

//获取模板名称
function getTemplateNameById(tId) {

    var tName = "";
    $.ajax({
        url: queryTemplateInfoUrl,
        type: 'get',
        async: false,
        data: {
            templateId: tId
        },
        success: function (d) {
            // console.log(d);
            if (JSON.parse(d).status == '0') {
                tName = JSON.parse(d).data.templateName;
            }
        }
    });
    return tName;
}

//选择模板-加载模板信息
function initLoadTemplatePage(tInfo) {

    var _tId = tInfo.split("\2")[0];
    var _tName = tInfo.split("\2")[1];
    var _tresolution = tInfo.split("\2")[2];
    var _url = tInfo.split("\2")[3];

    console.log(tInfo);

    $("#b_changeTemplate").prop("value", "更换模板");
    $("#hid_template_id").val(_tId);
    $("#hid_template_resolution").val(_tresolution);
    // $("#a_template_name").html(_tName);
    $("#b_changeTemplate").val(_tName);
    $("#hid_template_url").val(_url);
}

//加载医生列表
function queryDoctor(_selectPage) {

    var _html = "";
    _selectPage = _selectPage == undefined ? "1" : _selectPage;

    $.ajax({
        url: queryDoctorListUrl,
        type: 'get',
        data: {
            pageNumber: _selectPage,
            pageSize: 20,
            doctorName: "",
            deptId: $("#select_dept").val(),
            sortColumns: ""
        },
        success: function (d) {

            var jsonObj = JSON.parse(d);
            var trHtml = "";

            if (JSON.parse(d).status == "0") {
                var doctorList = jsonObj.data.list;

                for (var i = 0; i < doctorList.length; i++) {
                    var _doctorId = doctorList[i].doctorId;
                    var _doctorKey = doctorList[i].doctorKey;
                    var _doctorName = doctorList[i].doctorName;
                    var _deptId = doctorList[i].deptId;
                    var _doctorTitle = doctorList[i].doctorTitle;
                    var _isSpeciallyInvite = doctorList[i].isSpeciallyInvite;
                    var _intro = doctorList[i].intro;
                    var _workingPicture = doctorList[i].workingPicture;
                    var _deptName = doctorList[i].deptName == undefined ? "" : doctorList[i].deptName;


                    var _titledesc = _doctorTitle == "1" ? "住院医师" : _doctorTitle == "2" ? "主治医师"
                   : _doctorTitle == "3" ? "副主任医师" : _doctorTitle == "4" ? "主任医师" : _doctorTitle;


                    var _selectId = "select_showType_" + i;
                    var _selectHtml = "<select id='" + _selectId + "' onChange='setRowPosi(this)'>" +
                                        "<option value='1'>全显示</option>" +
                                        "<option value='2'>按排班</option>" +
                                        "<option value='3'>不显示</option>" +
                                      "</select>";

                    _html += "<tr  id='" + JSON.stringify(doctorList[i]) + "'>" +
                                 "<td>" + _doctorKey + "</td>" +
                                 "<td>" + _doctorName + "</td>" +
                                 "<td>" + _titledesc + "</td>" +
                                  "<td>" + _deptName + "</td>" +
                                 "<td>" + _selectHtml + "</td>" +
                                 "<td>" +
                                 "      <input type='button'  class='to-top' value='置顶' onclick='setToTop(this)'/>" +
                                 "      <input type='button'  class='move-top' value='上移' onclick='setMoveTop(this)'/>" +
                                  "     <input type='button' id='but_move_bottom'  class='move-bottom' value='下移' onclick='setMoveBottom(this)'/>" +
                                   "    <input type='button'  class='to-bottom' value='置底' onclick='setToBottom(this)'/>" +
                                 "</td>" +
                            +"</tr>";
                }

                $("#tbody_displayrule").html(_html);
            }
        }
    });
}

//编辑-加载数据
function loadDisplayRuleInfo() {
    //console.log(_disrule_id);

    $.ajax({
        url: queryDisplayRuleInfoUrl,
        type: 'get',
        data: {
            programId: _disrule_id

        },
        success: function (d) {
            //console.log(d);
            if (JSON.parse(d).status == '0') {

                var dataObj = JSON.parse(d).data;
                var docotrInfoArr = dataObj.data;

                var _programId = dataObj.programId;
                var _programName = dataObj.programName;
                var _templateId = dataObj.templateId;
                var _resolution = dataObj.resolution;
                var _url = dataObj.programURL;


                var _deptId = docotrInfoArr[0].deptId;


                $("#select_dept").find("option[value='" + _deptId + "']").attr("selected", true);

                $("#hid_proname").val(_programName);
                $("#hid_template_id").val(_templateId);
                $("#hid_template_resolution").val(_resolution);
                $("#hid_template_url").val(_url);
                $("#b_changeTemplate").val(getTemplateNameById(_templateId));
                //$("#a_template_name").html(getTemplateNameById(_templateId));


                var _html = "";
                for (var i = 0; i < docotrInfoArr.length; i++) {

                    var _doctorId = docotrInfoArr[i].doctorId;
                    var _doctorKey = docotrInfoArr[i].doctorKey;
                    var _doctorName = docotrInfoArr[i].doctorName;
                    var _deptId = docotrInfoArr[i].deptId;
                    var _doctorTitle = docotrInfoArr[i].doctorTitle;
                    var _isSpeciallyInvite = docotrInfoArr[i].isSpeciallyInvite;
                    var _intro = docotrInfoArr[i].intro;
                    var _workingPicture = docotrInfoArr[i].workingPicture;
                    var _rule = docotrInfoArr[i].rule;
                    var _deptName = docotrInfoArr[i].deptName == undefined ? "" : docotrInfoArr[i].deptName;


                    var _titledesc = _doctorTitle == "1" ? "住院医师" : _doctorTitle == "2" ? "主治医师"
                   : _doctorTitle == "3" ? "副主任医师" : _doctorTitle == "4" ? "主任医师" : _doctorTitle;

                    var _selectId = "select_showType_" + i;
                    var _selectHtml = "";
                    if (_rule == "1") {
                        _selectHtml = "<select id='" + _selectId + "' onChange='setRowPosi(this)'>" +
                                  "<option value='1' selected>全显示</option>" +
                                  "<option value='2'>按排班</option>" +
                                  "<option value='3'>不显示</option>" +
                                "</select>";
                    } else if (_rule == "2") {
                        console.log("----" + _rule);
                        _selectHtml = "<select id='" + _selectId + "' onChange='setRowPosi(this)'>" +
                                 "<option value='1' >全显示</option>" +
                                 "<option value='2' selected='selected'>按排班</option>" +
                                 "<option value='3'>不显示</option>" +
                               "</select>";
                    } else if (_rule == "3") {
                        _selectHtml = "<select id='" + _selectId + "' onChange='setRowPosi(this)'>" +
                                 "<option value='1' >全显示</option>" +
                                 "<option value='2'>按排班</option>" +
                                 "<option value='3' selected>不显示</option>" +
                               "</select>";
                    }

                    _html += "<tr  id='" + JSON.stringify(docotrInfoArr[i]) + "'>" +
                                 "<td>" + _doctorKey + "</td>" +
                                 "<td>" + _doctorName + "</td>" +
                                 "<td>" + _titledesc + "</td>" +
                                  "<td>" + _deptName + "</td>" +
                                 "<td>" + _selectHtml + "</td>" +
                                 "<td>" +
                                 "      <input type='button'  class='to-top' value='置顶' onclick='setToTop(this)'/>" +
                                 "      <input type='button'  class='move-top' value='上移' onclick='setMoveTop(this)'/>" +
                                  "     <input type='button' id='but_move_bottom'  class='move-bottom' value='下移' onclick='setMoveBottom(this)'/>" +
                                   "    <input type='button'  class='to-bottom' value='置底' onclick='setToBottom(this)'/>" +
                                 "</td>" +
                            +"</tr>";
                }

                $("#tbody_displayrule").html(_html);

                //queryDoctor();
            }
        }
    });
}

//新建或保存显示规则
function saveOrUpdateDisplayRule() {

    var _templateId = $("#hid_template_id").val();
    console.log(_templateId.length);
    if (_templateId == "") {
        layer.alert("请选择一个排班模板!", { icon: 7 });
        return;
    }

    //修改
    if (_disrule_id != "" && _disrule_id != null) {
        console.log(_disrule_id);

        var paraObj = new Object;
        paraObj.programId = _disrule_id;
        paraObj.programName = $("#hid_proname").val();
        paraObj.templateId = $("#hid_template_id").val();
        paraObj.programURL = $("#hid_template_url").val() + "?instance_id=" + paraObj.programId;
        paraObj.resolution = $("#hid_template_resolution").val();

        var ruleArray = new Array();
        var orderNum = 1;

        var _doctorLen = $("#tbody_displayrule tr").length;
        if (_doctorLen == 0) {
            layer.alert("该科室下没有医生数据，请选择有医生的科室。", { icon: 7 });
            return;
        }


        $("#tbody_displayrule tr").each(function () {

            var _jsonstr = JSON.parse($(this).prop("id"));
            var _doctorRuleObj = new Object;
            _doctorRuleObj.doctorId = _jsonstr.doctorId;
            _doctorRuleObj.rule = $(this).find("td:eq(4)").find("select").val();
            _doctorRuleObj.order = orderNum;
            ruleArray.push(_doctorRuleObj);
            orderNum++;
        });

        paraObj.programRule = ruleArray;
        //console.log(JSON.stringify(paraObj));

        $.ajax({
            url: updateDisplayRuleInfoUrl,
            data: {
                param: JSON.stringify(paraObj)
            },
            type: 'post',
            success: function (d) {
                console.log(d);
                if (JSON.parse(d).status == '0') {
                    layer.alert("保存成功", { icon: 1 });
                    loadDisplayRuleInfo();
                } else {
                    layer.alert("保存失败:" + JSON.parse(d).desc, { icon: 2 });
                }
            }
        });
    }
        //添加
    else {
        var style1 = "width:400px;height:30px;line-height:30px;text-align:center;margin-top:35px;";
        var style2 = "width:400px;height:30px;line-height:30px;text-align:center;margin-top:-4px;color:red";
        var html = "<div style=" + style1 + "><input style='width:200px;height:30px;border:1px solid #cccccc;background-color:white' type='text' id='text_ruleName' name='text_ruleName' /></div>";
        html += "<div style=" + style2 + " id='save_error'><span></span></div>";
        html += "<div style=" + style1 + "><input type='button' class='but_ok'  value='确认' onclick='newDisplayRule();'/></div>";

        layer.open({
            type: 1,
            title: "请输入新的规则名称",
            shadeClose: true,
            area: ['400px', '240px'],
            content: html,
        });
    }
}

//新建规则
function newDisplayRule() {

    var _displayRuleName = $("#text_ruleName").val();
    var _templateId = $("#hid_template_id").val();
    if (_displayRuleName == "") {
        $("#save_error").html("规则名称不能为空!");
        return;
    } else if (_templateId == "") {
        $("#save_error").html("请选择一个排班模板!");
        return;
    }

    else {

        var paraObj = new Object;
        paraObj.programName = _displayRuleName;
        paraObj.templateId = _templateId;
        paraObj.programURL = $("#hid_template_url").val() + "?instance_id=";
        paraObj.resolution = $("#hid_template_resolution").val();

        var ruleArray = new Array();
        var orderNum = 1;

        var _doctorLen = $("#tbody_displayrule tr").length;
        if (_doctorLen == 0) {
            layer.alert("该科室下没有医生数据，请选择有医生的科室。", { icon: 7 });
            return;
        }

        $("#tbody_displayrule tr").each(function () {

            var _jsonstr = JSON.parse($(this).prop("id"));
            var _doctorRuleObj = new Object;
            _doctorRuleObj.doctorId = _jsonstr.doctorId;
            _doctorRuleObj.rule = $(this).find("td:eq(4)").find("select").val();
            _doctorRuleObj.order = orderNum;
            ruleArray.push(_doctorRuleObj);
            orderNum++;
        });

        paraObj.programRule = ruleArray;
        //console.log(JSON.stringify(paraObj));
        $.ajax({
            url: newDisplayRuleUrl,
            data: {
                param: JSON.stringify(paraObj)
            },
            type: 'post',
            success: function (d) {
                // console.log(d);
                if (JSON.parse(d).status == '0') {
                    window.location.href = "../arrange/arrange_list.html?index=2"
                } else {
                    var _desc = JSON.parse(d).desc;
                    layer.alert(_desc);
                }
            }
        });
    }
}

//设置医生显示位置
function setRowPosi(t) {

    var _rowType = $(t).val();
    console.log(_rowType);

    var $_tr = $(t).parents("tr");

    //置顶
    if (_rowType == "1") {
        $_tr.fadeOut().fadeIn();
        $("#tbody_displayrule").prepend($_tr);
    }
        //置底
    else if (_rowType == "3") {
        $_tr.fadeOut().fadeIn();
        $("#tbody_displayrule").append($_tr);
    }
}

//置顶
function setToTop(t) {

    var $tr = $(t).parents("tr");
    $tr.fadeOut().fadeIn();
    $("#tbody_displayrule").prepend($tr);
}

//上移
function setMoveTop(t) {

    var $tr = $(t).parents("tr");
    if ($tr.index() != 0) {
        $tr.fadeOut().fadeIn();
        $tr.prev().before($tr);
    }
}

//下移
function setMoveBottom(t) {

    var $down = $("#but_move_bottom");
    var len = $down.length;
    var $tr = $(t).parents("tr");

    if ($tr.index() != len - 1 || $tr.index() == 0) {
        $tr.fadeOut().fadeIn();
        $tr.next().after($tr);
    }
}

//置底
function setToBottom(t) {

    var $tr = $(t).parents("tr");
    $tr.fadeOut().fadeIn();
    $("#tbody_displayrule").append($tr);

}


function loadDoctorInfoTablePagin(jData) {
    //异步加载数据
    var _startNumPage = jData.data.pageNum;
    var _sumNumPage = jData.data.pages;

    console.log(_startNumPage + "__" + _sumNumPage);
    Page({
        num: _sumNumPage,					        //总页码数
        startnum: _startNumPage,					//指定页码
        elem: $('#page2'),	                        //指定的元素
        callback: function (n) {	                //回调函数
            console.log(n);
            queryDoctor(n);
        }
    });
}
